from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel
from app.core.database import get_db
from app.core.deps import get_current_admin_user
from app.models.user import User
from app.models.system_config import SystemConfig

router = APIRouter()

class ConfigResponse(BaseModel):
    id: int
    config_key: str
    config_value: str
    config_type: Optional[str] = None
    description: Optional[str] = None

    class Config:
        from_attributes = True

class ConfigUpdate(BaseModel):
    config_value: str
    description: Optional[str] = None

@router.get("", response_model=List[ConfigResponse])
def get_configs(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    configs = db.query(SystemConfig).all()
    return configs

@router.get("/{config_key}", response_model=ConfigResponse)
def get_config(
    config_key: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    config = db.query(SystemConfig).filter(
        SystemConfig.config_key == config_key
    ).first()
    if not config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="配置不存在"
        )
    return config

@router.put("/{config_key}", response_model=ConfigResponse)
def update_config(
    config_key: str,
    config_update: ConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    config = db.query(SystemConfig).filter(
        SystemConfig.config_key == config_key
    ).first()
    
    if not config:
        config = SystemConfig(
            config_key=config_key,
            config_value=config_update.config_value,
            description=config_update.description
        )
        db.add(config)
    else:
        config.config_value = config_update.config_value
        if config_update.description:
            config.description = config_update.description
    
    db.commit()
    db.refresh(config)
    return config

